package com.qf.springbootproject.shiro;

import cn.hutool.jwt.JWT;
import com.qf.springbootproject.config.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

//@Component("jwt")
@Slf4j
public class JwtShiroFilter extends AccessControlFilter {
    /**
     * 返回true 请求可以继续执行；返回false请求会被onAccessDenied方法处理
     *
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        log.debug("============isAccessAllowed=============");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //从请求头中获取token
        //如果请求头中没有携带token，则直接拒绝请求
        String token = req.getHeader("token");
        if (token == null || "".equals(token)) {
            log.debug("没有携带token");
            return false;
        }
        //校验token的合法性
        boolean validate = JWT.of(token).setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8))
                .validate(0);
        if (validate) {
            //token合法
            log.debug("token合法");
            return true;
        } else {
            //token不合法
            log.debug("token不合法");
            return false;

        }
    }

    /**
     * 当上面的方法返回false时会进入如下方法
     * 该方法返回true。请求依然会继续向下执行，如果返回false，则请求不向下执行
     * 在jwt校验场景下推荐返回false
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        servletResponse.getWriter().println("token not ok");
        log.debug("token有问题");
        return false;
    }
}
